package com.lagou.备份;

import com.lagou.client.UserClientHandler;
import com.lagou.service.JSONSerializer;
import com.lagou.service.RpcEncoder;
import com.lagou.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler=null;

    private static EventLoopGroup group;

    private static Bootstrap bootstrap;
    private static ChannelFuture channelFuture;


    private static final int MAX_RETRY = 5;
    private static Channel channel;
    private static Boolean ifConnecting = false;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass,String ip,int port){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法

                if(userClientHandler == null){
                 initClient(ip, port);
                }


                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
//                System.out.println(requestId);

                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);



                // 设置参数
//                userClientHandler.setPara(request);
//                System.out.println(request);
//                System.out.println("设置参数完成");

                // 去服务端请求数据

                Object o =executor.submit(userClientHandler).get();

                if (userClientHandler.getResult().equals("success")){
                    System.out.println("服务器"+ip+":"+port+"已响应");
                }else {

                    System.out.println(userClientHandler.getResult());

                    if (!channelFuture.channel().isActive()& !ifConnecting) {
                        System.out.println("尝试重连");
                        connect(RpcConsumer.getBootstrap(), ip, port, MAX_RETRY);
                        Thread.sleep(2000);
                    }


//                    group.shutdownGracefully();
//                    channelFuture.channel().closeFuture().sync();
//                    channelFuture =bootstrap.connect(ip, port).sync();
                }

                return o;



            }
        });


    }



    //2.初始化netty客户端
    public static  void initClient(String ip,int port) throws InterruptedException {

            userClientHandler = new UserClientHandler();

            group = new NioEventLoopGroup();

            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                            pipeline.addLast(new StringDecoder());
//                            pipeline.addLast(new ReadTimeoutHandler(5));
                            pipeline.addLast(userClientHandler);
                        }
                    });


//            channelFuture =bootstrap.connect(ip, port).sync();
//            future.channel().closeFuture().sync();// 阻塞main线程

            connect(bootstrap,ip,port,MAX_RETRY);

    }



    /**
     * 失败重连机制，参考Netty入门实战掘金小册
     *
     */
    public synchronized static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        ifConnecting=true;
        channelFuture = bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接服务端成功");
                ifConnecting=false;
            } else if (retry == 0) {
                System.out.println("重试次数已用完，放弃连接");
                ifConnecting=false;
            } else {
                //第几次重连：
                int order = (MAX_RETRY - retry) + 1;
                //本次重连的间隔
                int delay = 1 << order;
                System.out.println(new Date()+"{} : 连接失败，第 "+order+" 次重连....");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
            }
        });
        channel = channelFuture.channel();
    }

    public static ChannelFuture getChannelFuture() {
        return channelFuture;
    }

    public static int getMaxRetry() {
        return MAX_RETRY;
    }

    public static Channel getChannel() {
        return channel;
    }


    public static Bootstrap getBootstrap() {
        return bootstrap;
    }
}


